;;; Lispy-Fennel (LF) --- The Functional Fennel Library
;;;
;;; Copyright (C) 2020 Kevin "The Nuclear" Bloom <nuclearkev@dragora.org>
;;;
;;; This file is part of LF.
;;;
;;; LF is free software: you can redistribute it and/or modify
;;; it under the terms of the MIT License.
;;;
;;; LF is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; MIT License for more details.
;;;
;;; You should have received a copy of the MIT License
;;; along with LF.  If not, see <https://opensource.org/licenses/MIT>.

(local iteration {})

(fn iteration.map [f l]
    (var map [])
    (when (> (length l) 0)
      (each
       [k v (ipairs l)]
       (table.insert map (f v))))
    map)

(fn iteration.filter [f l]
    (var filtered [])
    (each
     [k v (ipairs l)]
     (when (f v)
       (table.insert filtered v)))
    filtered)

(fn iteration.filter-map [f l]
    (var filtered [])
    (each
     [k v (ipairs l)]
     (let [new-v (f v)]
       (when new-v
         (table.insert filtered new-v))))
    filtered)

(fn iteration.reduce [f d l]
    (var prev d)
    (each
     [k cur (ipairs l)]
     (let [new-v (f prev cur)]
       (set prev new-v)))
    prev)

iteration
